import WebSocket from 'ws';
import { validAuth } from '../auth';
import { sv } from './server';
import type { GameMsg, CustomSocket } from './types';

process.on('uncaughtException', function (e) {
  /*处理异常*/
  console.log(e.message);
});

const server = new WebSocket.Server({ port: 9999 }, () => {
  console.log('WebSocket server started on port 9999');
});

server.on('connection', async (socket: CustomSocket, req: any) => {
  const accessToken = req.headers['sec-websocket-protocol'];
  console.log('Client connected');
  // 验证OAuth令牌的合法性
  try {
    const user_id = await validAuth(accessToken);
    if (user_id) {
      // 鉴权通过，进行后续操作
      // socket.send('鉴权通过，欢迎连接！');
      socket['user_id'] = user_id;
    } else {
      // 鉴权失败，关闭连接
      socket.close();
    }
  } catch (error) {
    // 验证失败，关闭连接
    socket.close();
  }

  // 处理收到的消息
  socket.on('message', (msg: Buffer) => {
    const {
      user_id,
    }: {
      user_id: string;
    } = socket;
    try {
      console.log(`Received: ${msg}`);
      console.log(typeof msg);
      console.log(msg.toString());
      const jMsg: GameMsg = JSON.parse(msg.toString());

      sv(user_id, jMsg)
        ?.then((res: any): void => {
          const rep = {
            id: jMsg.id * 10 + 1,
            data: res,
          };
          console.log(rep);
          socket.send(JSON.stringify(rep));
        })
        .catch((error: any): void => {
          console.log(error);
          const rep = {
            id: jMsg.id * 10 + 2,
            data: error,
          };
          socket.send(JSON.stringify(rep));
        });
    } catch (error) {
      console.error('Error parsing JSON:', error);
    }
  });

  // 处理连接关闭
  socket.on('close', () => {
    console.log('Client disconnected');
  });
});
